﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Channels;
using System.Configuration;
using System.Security.Cryptography;

namespace Amazon.Route53.WCFExtension
{
    public class AuthenticationMessageInspector : IClientMessageInspector
    {

        private String AWSAccessKey
        {
            get;
            set;
        }
        private String AWSSecretKey
        {
            get;
            set;
        }

        public AuthenticationMessageInspector(String accessKey, String secretKey)
        {
            this.AWSAccessKey = accessKey;
            this.AWSSecretKey = secretKey;
        }

        #region IClientMessageInspector Members

        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {

        }
        //
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            HttpRequestMessageProperty httpRequestMessage;

            object httpRequestMessageObject;

            if (request.Properties.TryGetValue(HttpRequestMessageProperty.Name, out httpRequestMessageObject))
            {

                httpRequestMessage = httpRequestMessageObject as HttpRequestMessageProperty;

            }

            else
            {

                httpRequestMessage = new HttpRequestMessageProperty();

                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage);
            }
            string Date = Amazon.Util.AWSSDKUtils.FormattedCurrentTimestampGMT;
            String hashedString = Amazon.Util.AWSSDKUtils.HMACSign(Date, AWSSecretKey, new HMACSHA1());
            String Signature = String.Format("AWS3-HTTPS AWSAccessKeyId={0},Algorithm=HmacSHA1,Signature={1}", AWSAccessKey, hashedString);
            httpRequestMessage.Headers["x-amz-date"] = Date;
            httpRequestMessage.Headers["X-Amzn-Authorization"] = Signature;
            httpRequestMessage.Headers["x-amz-request-id"] = Guid.NewGuid().ToString();

            return null;
        }


        #endregion
    }
}
